class MySingleLinkedList {
    static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode head;//代表链表的头结点

    public void display() {
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    public void display(ListNode newHead) {
        ListNode cur = newHead;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    public void addFirst(int val) {
        ListNode node = new ListNode(val);
        node.next = head;
        head = node;
    }

    //找出并返回链表的中间结点
    public ListNode middleNode() {
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

}

public class Demo2_3 {
    //链表的中间结点
    //给你单链表的头结点 head ，请你找出并返回链表的中间结点。
    //如果有两个中间结点，则返回第二个中间结点。
    public static void main(String[] args) {
        MySingleLinkedList msl = new MySingleLinkedList();
        msl.addFirst(5);
        msl.addFirst(6);
        msl.addFirst(4);
        msl.addFirst(8);
        msl.addFirst(10);
        msl.display();
        System.out.println("======");
        MySingleLinkedList.ListNode ret =msl.middleNode();
        System.out.println(ret.val);
    }
}
